<template>
  <div class="merchants-page">
    <!-- 搜索和筛选区域 -->
    <el-card shadow="never" class="search-card">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="关键词">
          <el-input
            v-model="searchForm.keyword"
            placeholder="商家名称/电话/地址"
            clearable
            style="width: 200px"
            @clear="handleSearch"
          />
        </el-form-item>
        
        <el-form-item label="状态">
          <el-select
            v-model="searchForm.status"
            placeholder="全部"
            clearable
            style="width: 120px"
            @change="handleSearch"
          >
            <el-option label="营业中" :value="1" />
            <el-option label="休息中" :value="0" />
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
          <el-button :icon="Refresh" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计信息 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <el-statistic title="总商家数" :value="statistics.totalMerchants || 0" />
      </el-col>
      <el-col :span="6">
        <el-statistic title="营业中" :value="statistics.activeCount || 0" />
      </el-col>
      <el-col :span="6">
        <el-statistic title="总商品数" :value="statistics.totalFoods || 0" />
      </el-col>
      <el-col :span="6">
        <el-statistic title="总订单数" :value="statistics.totalOrders || 0" />
      </el-col>
    </el-row>

    <!-- 商家列表 -->
    <el-card shadow="never" class="table-card">
      <el-table
        v-loading="loading"
        :data="merchantList"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        
        <el-table-column label="商家信息" min-width="250">
          <template #default="{ row }">
            <div class="merchant-info">
              <el-avatar :src="row.logo" :size="50" shape="square">
                {{ row.name?.charAt(0) }}
              </el-avatar>
              <div class="merchant-detail">
                <div class="name">{{ row.name }}</div>
                <div class="desc">{{ row.description || '暂无描述' }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="联系方式" width="180">
          <template #default="{ row }">
            <div>电话：{{ row.phone }}</div>
            <div class="address">{{ row.address }}</div>
          </template>
        </el-table-column>
        
        <el-table-column label="配送信息" width="150">
          <template #default="{ row }">
            <div>起送：¥{{ row.minOrderAmount }}</div>
            <div>配送费：¥{{ row.deliveryFee }}</div>
          </template>
        </el-table-column>
        
        <el-table-column label="评分" width="100">
          <template #default="{ row }">
            <el-rate
              v-model="row.rating"
              disabled
              show-score
              text-color="#ff9900"
            />
            <div style="font-size: 12px; color: #909399;">
              {{ row.ratingCount }} 评价
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag v-if="row.status === 1" type="success">营业中</el-tag>
            <el-tag v-else type="info">休息中</el-tag>
          </template>
        </el-table-column>
        
        <el-table-column label="数据统计" width="150">
          <template #default="{ row }">
            <div>商品：{{ row.foodCount || 0 }}</div>
            <div>订单：{{ row.orderCount || 0 }}</div>
            <div>营收：¥{{ row.totalRevenue || '0.00' }}</div>
          </template>
        </el-table-column>
        
        <el-table-column label="所有者" width="120">
          <template #default="{ row }">
            <div v-if="row.ownerUsername">
              {{ row.ownerUsername }}
            </div>
            <el-tag v-else type="info" size="small">未绑定</el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="createdAt" label="创建时间" width="180" />
        
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button
              :type="row.status === 1 ? 'warning' : 'success'"
              size="small"
              @click="handleToggleStatus(row)"
            >
              {{ row.status === 1 ? '休息' : '营业' }}
            </el-button>
            
            <el-button
              type="danger"
              size="small"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.totalItems"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>



<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh } from '@element-plus/icons-vue'
import { getMerchantList, updateMerchantStatus, deleteMerchant } from '@/api/merchants'

const loading = ref(false)
const merchantList = ref([])
const statistics = ref({})
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  totalItems: 0,
  totalPages: 0
})

const searchForm = reactive({
  keyword: '',
  status: ''
})

// 加载商家列表
const loadMerchantList = async () => {
  loading.value = true
  
  try {
    const params = {
      page: pagination.currentPage,
      size: pagination.pageSize,
      sortBy: 'createdAt',
      sortOrder: 'desc'
    }
    
    if (searchForm.keyword) params.keyword = searchForm.keyword
    if (searchForm.status !== '') params.status = searchForm.status
    
    const res = await getMerchantList(params)
    
    merchantList.value = res.data.items
    statistics.value = res.data.statistics
    pagination.totalItems = res.data.pagination.totalItems
    pagination.totalPages = res.data.pagination.totalPages
  } catch (error) {
    console.error('加载商家列表失败：', error)
    ElMessage.error('加载商家列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  loadMerchantList()
}

// 重置
const handleReset = () => {
  searchForm.keyword = ''
  searchForm.status = ''
  pagination.currentPage = 1
  loadMerchantList()
}

// 切换商家状态
const handleToggleStatus = (row) => {
  const newStatus = row.status === 1 ? 0 : 1
  const action = newStatus === 1 ? '营业中' : '休息中'
  
  ElMessageBox.confirm(`确定要将商家 ${row.name} 设置为${action}吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await updateMerchantStatus(row.id, newStatus)
      ElMessage.success(`设置为${action}`)
      loadMerchantList()
    } catch (error) {
      console.error('更新商家状态失败：', error)
      ElMessage.error('更新状态失败')
    }
  }).catch(() => {})
}

// 删除商家
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除商家 ${row.name} 吗？删除后数据将无法恢复！`,
    '危险操作',
    {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'error'
    }
  ).then(async () => {
    try {
      await deleteMerchant(row.id)
      ElMessage.success('删除成功')
      loadMerchantList()
    } catch (error) {
      console.error('删除商家失败：', error)
      ElMessage.error(error.message || '删除失败')
    }
  }).catch(() => {})
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.currentPage = 1
  loadMerchantList()
}

// 当前页改变
const handleCurrentChange = (page) => {
  pagination.currentPage = page
  loadMerchantList()
}

onMounted(() => {
  loadMerchantList()
})
</script>



<style scoped>
.merchants-page {
  width: 100%;
}

.search-card {
  margin-bottom: 20px;
}

.stats-row {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.merchant-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.merchant-detail {
  flex: 1;
}

.name {
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
}

.desc {
  font-size: 12px;
  color: #909399;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.address {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
